<%@ page language="java" contentType="text/html; charset=utf-8"%>
<html>
<head>
<%@ include file="/extjs/include/all.jsp"%>
<link href="${pageContext.request.contextPath}/edu.ccut.saturn.authority.impl/userModule/page/css/authority.css" rel="stylesheet" type="text/css">
<title>用户管理</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/extjs/js/validate.js"></script>
</head>
<body>
<div id="userForm" style="width:100%"></div>
<div id="result" style="width:100%"></div>
<div id="selectUser" style="width:100%"></div>
<div id="selectRole" style="width:100%"></div>
</body>
</html>
<script>
var submitFunc;
var submitFuncRole;
Ext.onReady(function(){

  	Ext.QuickTips.init();  
  	<%@ include file="jsp/store.jsp" %>
	//-------------------------------------------------------------------------
	// 			查询表单
	//
	//-------------------------------------------------------------------------
	
    var top = new Ext.FormPanel({
        frame:true,//frame为false 背景为白色 
        title: '查询用户',
        bodyStyle:'padding:5px 5px 0',
        collapsible:true,
        renderTo:'userForm', //选择div
        labelWidth:60,
        items: [{
            layout:'column',
            items:[{
                columnWidth:.3,
                layout: 'form', 
                items: [{
                    xtype:'textfield',
                    fieldLabel: '登录名',
                    labelWidth:75,
                    name: 'userId_filter',
                    id:'userId_filter',
                    maxLength:10,
                    vtype: 'isNumberAlphaUnderlineChineseNotStartNumber',
                    anchor:'80%'
                }] 
            },{
                columnWidth:.3,
                layout: 'form',
                items: [{
                    xtype:'textfield',
                    fieldLabel: '姓名',
                    name: 'userName_filter',
                    id: 'userName_filter',
                    maxLength:10,
                    vtype: 'isNumberAlphaUnderlineChinese',
                    anchor:'80%'
                }]
            },{
                columnWidth:.3,
                layout: 'form',
                items: [{
                    xtype:'combo',
                    fieldLabel: '机构名称',
                    name: 'deptId_show',
                    id:'deptId_show',
                    store: dept_store,
			        displayField:'value',
			        valueField :'key', 
			        hiddenName: 'deptId',
			        typeAhead: true,
			        mode: 'local',
			        forceSelection: true,
			        triggerAction: 'all',
			        emptyText:'请选择机构...',
			        selectOnFocus:true,
			        editable: false,
                    anchor:'95%'
                }]
            }]
        }],

        buttons: [{
            text: '查询',
            handler:function(){
            	if (top.form.isValid()) {
		       		ds.load({params:{						
		       				start:0, limit:20,
								userId:Ext.get("userId_filter").dom.value,
								userName:Ext.get("userName_filter").dom.value,
								deptId:Ext.get("deptId").dom.value
								}}); 
		
		       	grid.getView().refresh();
       			} else {
       				Ext.MessageBox.alert('警告','对不起,您的页面输入有误');
       			}
            }
        }]
    });
	document.getElementById('userId_filter').maxLength = 10;
	document.getElementById('userName_filter').maxLength = 10;
	//-------------------------------------------------------------------------
	// 			下面的是表格
	//
	//-------------------------------------------------------------------------
	
	var sm = new Ext.grid.CheckboxSelectionModel();
	var resultWidth = Ext.get("result").getWidth();
	var cm = new Ext.grid.ColumnModel([ 
	    new Ext.grid.RowNumberer(), //table's index id
	    sm, 
        {header:'登录名',dataIndex:'id',width:resultWidth*0.2,sortable:true,renderer:function(value, p, record){ 

	        return String.format("<a href=\"javascript:submitFunc('{0}','{1}')\">{0}</a>", 
			        value,
			        record.data.name
	        );
	    }},  
        {header:'姓名',dataIndex:'username',width:resultWidth*0.15,sortable:true}, 
        {header:'描述',dataIndex:'descn',width:resultWidth*0.15,sortable:true}, 
        {header:'机构',dataIndex:'name',width:resultWidth*0.15,sortable:true},
        {header:'职位',dataIndex:'position_dict',width:resultWidth*0.15,sortable:true}, 
        {header:'操作',dataIndex:'',width:resultWidth*0.15,sortable:true,renderer:function(value, p, record){
        	return String.format("<a href=\"javascript:submitFuncRole('{0}')\">角色</a>", record.data.id);
        }}
    ]); 
    cm.defaultSortable = true; 
 	var ds = new Ext.data.Store({ 
        proxy: new Ext.data.HttpProxy({
        	url:'${pageContext.request.contextPath}/edu.ccut.saturn.authority.impl::/userModule/action/QueryUserList.action'
        }), 
        reader: new Ext.data.JsonReader({ 
                totalProperty: 'userCount', 
                root: 'result' 
	    }, 
	    [ 
	        {name: 'id',mapping:'id'}, 
	        {name: 'username',mapping:'username'}, 
	        {name: 'descn',mapping:'descn'}, 
	        {name: 'name',mapping:'name'} ,
	        {name: 'position_dict',mapping:'position_dict'},
	        {name: 'dept_id',mapping:'dept_id'} ,
	        {name: 'usertype',mapping:'usertype'}
	    ])
    }); 
			       
	var grid = new Ext.grid.GridPanel({ 
	    el: 'result', 
	    title:'用户列表', 
	    height:600, 
	    stripeRows: true,
	    collapsible:true,
	    trackMouseOver:false, 
	    bodyStyle:'width:100%',
	    loadMask: {msg:'正在加载数据，请稍侯……'}, 
	    store:ds, 
	    cm: cm, 
	    sm:sm, 
	    tbar: [{
            text:'添加用户',
            tooltip:'添加用户',
            iconCls:'add',
            handler: function(){
            	window.location = '${pageContext.request.contextPath}/edu.ccut.saturn.authority.impl/userModule/page/userInsert.jsp'
            }
        }, '-',{
            text:'删除用户',
            tooltip:'删除用户',
            iconCls:'remove',
            handler : remove
        }],
	    bbar: new Ext.PagingToolbar({ 
	            pageSize: 20, 
	            store: ds, 
	            displayInfo: true, 
	            displayMsg: '当前显示 {0} - {1}条记录 /共 {2}条记录', 
	            emptyMsg: "没有数据显示" 
	    }) 
	}); 
			
	ds.load({params:{start:0, limit:20}}); 
    grid.render(); 	
    
	ds.on('beforeload',function(){
		      Ext.apply(
		      this.baseParams,
		      {
	         		userId:Ext.get("userId_filter").dom.value,
					userName:Ext.get("userName_filter").dom.value,
					deptId:Ext.get("deptId").dom.value
		      });
		      if(!(top.form.isValid())){
			      	Ext.MessageBox.alert('警告','对不起，您的查询条件有误');
		    		return false;
	    	 }
    	 }	
    );
			    
	//--------------------------------------------------------------------------------------------
	//						删除用户
	//
	//
	//
	//
	//--------------------------------------------------------------------------------------------
  	function remove(){
  	
  		arr_Records = sm.getSelections();
	    if (arr_Records.length == 0) {
	        Ext.MessageBox.alert('警告', '最少需要选择一条记录!');
	    } else {
			Ext.MessageBox.confirm('确认', '确认删除所选信息?', delUser);
		}
	}
	function delUser(btn){

        if(btn == 'yes'){
	        arr_Records = sm.getSelections();
	        var delStr = ''; 		 
	   	   	for (var i = 0, len = arr_Records.length; i < len; i++){    
	   	   	  	 
	   	   	  	 delStr += arr_Records[i].data.id;  
	   	   	  	 delStr += ',' ;	
			} 
		    if(delStr.length > 0){
 					delStr = delStr.substring(0,delStr.length - 1) ;
			}
			Ext.Ajax.request({
			     method : 'POST',                             //发送方式.'POST'或'GET',一般是'POST'
			     url: '${pageContext.request.contextPath}/edu.ccut.saturn.authority.impl::/userModule/action/DeleteUser.action',                  //发送到页面
			     success:function(request){                   //发送成功的回调函数
			       var myResult = Ext.util.JSON.decode(request.responseText);
			       Ext.Msg.alert('信息',myResult.message, function(){
			       		ds.load({params:{start:0, limit:20}}); //重新刷新table
			       });        //弹出对话框
			     },
			     failure:function(){                          //发送失败的回调函数
			       Ext.Msg.alert("错误", "与后台联系的时候出现了问题");
			     },
			     params:{
			     		userSerialnoObject:delStr 
			     } 
	     	});
        	
        } 
		  
    }; 
	//--------------------------------------------------------------------------------------------
	//						下面是修改用户和添加角色
	//
	//--------------------------------------------------------------------------------------------    
  	
	submitFunc = function(id,dept_name){
		Ext.get("id").dom.value = id;
		Ext.get("dept_name").dom.value = dept_name;

		var form = selectUser.getForm().getEl().dom;   
        form.action = '${pageContext.request.contextPath}/edu.ccut.saturn.authority.impl/userModule/page/userEdit.jsp';   
        form.target='_self';   
        form.submit(); 
	};
	
	submitFuncRole = function(id){
		Ext.get("userId").dom.value = id;
		var form = selectRole.getForm().getEl().dom;   
        form.action = '${pageContext.request.contextPath}/edu.ccut.saturn.authority.impl/userModule/page/userRoleList.jsp';   
        form.target='_self';   
        form.submit(); 
	} ; 
	
	var selectUser = new Ext.FormPanel({
    	id:'selectUser',
        labelWidth: 75, 
        frame:true,
        title: 'selectUser',
        bodyStyle:'padding:5px 5px 0',
        defaults: {width: 230},
        defaultType: 'textfield',
        items: [{
                name: 'id',
                id: 'id'
            },{
                name: 'dept_name',
                id: 'dept_name'
            }
        ]
    });
    selectUser.render('selectUser');
    selectUser.hide();
    
    var selectRole = new Ext.FormPanel({
    	id:'selectRole',
        labelWidth: 75, 
        frame:true,
        title: 'selectRole',
        bodyStyle:'padding:5px 5px 0',
        defaults: {width: 230},
        defaultType: 'textfield',
        items: [{
                name: 'userId',
                id: 'userId'
            }
        ]
    });
    selectRole.render('selectRole');
    selectRole.hide();
});
</script>